#include "Driver_BSTIM32.h"

/**
 * @brief 初始化基本定时器 BSTIM32, 100ms溢出一次
 *
 */
void Driver_BSTIM32_Init(void)
{
    FL_BSTIM32_InitTypeDef bstim32Init = { 0 };

    bstim32Init.clockSource     = FL_CMU_BSTIM32_CLK_SOURCE_APBCLK;
    bstim32Init.prescaler       = 6400 - 1;
    bstim32Init.autoReload      = 1000 - 1; // 1000
    bstim32Init.autoReloadState = FL_ENABLE;

    FL_BSTIM32_Init(BSTIM32, &bstim32Init);

    FL_BSTIM32_ClearFlag_Update(BSTIM32); /* 清除计数器中断标志位 */
    FL_BSTIM32_EnableIT_Update(BSTIM32);  /* 开启计数器中断 */

    NVIC_DisableIRQ(BSTIM_IRQn);
    NVIC_SetPriority(BSTIM_IRQn, 2);      /* TODO 中断优先级配置 */
    NVIC_EnableIRQ(BSTIM_IRQn);

    FL_BSTIM32_Enable(BSTIM32);           /* 使能定时器 */
}

// extern void BSTIM_IRQHandler_LongDistance(void);

/**
 * @brief BSTIM中断服务程序, 100ms触发一次
 *
 */
void BSTIM_IRQHandler(void)
{
    // BSTIM_IRQHandler_LongDistance();

    /* 用于控制腰托按键时间 */
    if (FL_BSTIM32_IsEnabledIT_Update(BSTIM32) && FL_BSTIM32_IsActiveFlag_Update(BSTIM32)) {
        FL_BSTIM32_ClearFlag_Update(BSTIM32);

        for (uint8_t i = 0; i < LUMBAR_SUPPORT_MAXSIZE; ++i) {
            if (lumbarSupports[i].state == YT_STATE_IDLE) {
                continue;
            }
            else if (lumbarSupports[i].state == YT_STATE_INFLATION) {
                lumbarSupports[i].inflatedTime =
                    (lumbarSupports[i].inflatedTime == lumbarSupports[i].fullPressure)
                        ? lumbarSupports[i].fullPressure
                        : ++lumbarSupports[i].inflatedTime;
            }
            else if (lumbarSupports[i].state == YT_STATE_DEFLATION) {
                lumbarSupports[i].inflatedTime =
                    (lumbarSupports[i].inflatedTime == 0) ? 0 : --lumbarSupports[i].inflatedTime;
            }
        }
    }
}
